package com.upsuns.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.logging.Logger;

import com.upsuns.util.Constants;

/**
 *@Description:<p>客户端，基于Netty的NIO模型</p>
 *@author 王旭
 *@time 2016年3月18日 下午11:40:56
 */
public class TimeClientHandler extends ChannelHandlerAdapter {
	
	public TimeClientHandler() {}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
//		super.channelActive(ctx);
		byte[] req = Constants.TIME_QUERY.getBytes(); //获取请求信息
		ByteBuf buf = Unpooled.buffer(req.length);
		buf.writeBytes(req); //把请求信息写入到buf中
		ctx.writeAndFlush(buf); //发送至服务器
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
//		super.channelRead(ctx, msg);
		ByteBuf buf = (ByteBuf) msg;
		byte[] resp = new byte[buf.readableBytes()];
		buf.readBytes(resp); //读取返回信息
		String respStr = new String(resp, "utf-8");
		System.out.println("响应信息：" + respStr); //打印相应信息
	}
	
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
//		super.exceptionCaught(ctx, cause);
		System.out.println("error:" + cause.getMessage());
		ctx.close();
	}
	
}
